import { Storage } from "./storage";
import { authApi } from "../api";

const TOKEN_KEY = "token";
const TOKEN_DURATION = 12 * 60 * 60 * 1000; // token有效期
const TOKEN_REFRESH = TOKEN_DURATION / 2; // 在token失效前TOKEN_REFRESH毫秒刷新

export class Token {
  static set(value) {
    Storage.set(TOKEN_KEY, value, TOKEN_DURATION);
  }
  static exist() {
    return !!Token.get();
  }
  static get() {
    return Storage.get(TOKEN_KEY);
  }
  static remove() {
    Storage.remove(TOKEN_KEY);
  }
  static async refresh() {
    if (Storage.getExpire(TOKEN_KEY) < new Date().getTime() + TOKEN_REFRESH) {
      // 只在token失效前TOKEN_REFRESH毫秒刷新
      this.refreshImmediate();
    }
  }

  static async refreshImmediate() {
    const { code, data } = await authApi.refreshToken();
    if (code !== 1) return;
    Token.set(data.token);
  }
}
